package org.annoflow.filter.sqli;

import java.util.HashMap;

import org.annoflow.audit.ContextTracker;
import org.annoflow.audit.Logger;
import org.annoflow.filter.FilterPoint;
import org.annoflow.policy.PolicyManager;
import org.annoflow.policy.PolicyType;

public class SQLBoundFilter implements FilterPoint {

	@Override
	public String getFilterCode() {
		return "org.annoflow.filter.sqli.SQLBoundFilter.runFilter($args);";
	}

	public static void runFilter(Object[] args) throws Exception {
		for (Object arg : args) {
			if (arg instanceof String) {
				String potentialSQL = (String) arg;
				if (containsSQL(potentialSQL)) {
//					StackTraceElement[] elements = Thread.currentThread().getStackTrace();
					Logger.error(SQLBoundFilter.class.getName(),ContextTracker.getInstance().getFilterContext(),arg,"Suspicious SQL: " + arg);
					throw new Exception();
				}
			}
			
//			//Next check if there's a policy on the object being passed in
//			PolicyType policy = null;
//			if ((policy = PolicyManager.lookupObjectPolicy(arg)) != null) {
//				HashMap<String,String> context = new HashMap<String, String>();
//				context.put("target", "sql");
//				policy.assess(context);
//			}
//			
//			//Finally check if there's a policy on any of the object's fields
//			HashMap<Object,PolicyType> fields = null;
//			if((fields = PolicyManager.lookupParentPolicy(arg)) != null) {
//				HashMap<String,String> context = new HashMap<String, String>();
//				context.put("target", "sql");
//				for (Object field : fields.keySet()) {
//					fields.get(field).assess(context);
//				}
//			}
		}
	}

	private static boolean containsSQL(String potential) {
		return potential.contains("WHERE") || potential.contains("SELECT")
				|| potential.contains("DROP") || potential.contains("TRUNCATE");
	}

	@Override
	public String getReturnFilterCode() {
		// TODO Auto-generated method stub
		return null;
	}

}
